package com.supostacks.infrastructure.context;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class DefaultContext {

    public boolean ignoreField(String key) {
        String ignoreFields = "pageNo,pageSize,orderBy";
        return ignoreFields.contains(key);
    }

    public <T> QueryWrapper<T> where(JSONObject params) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        for (String key : params.keySet()) {
            if (ignoreField(key)) {
                continue;
            }
            JSONArray jsonArray = params.getJSONArray(key);
            if (jsonArray != null && jsonArray.size() > 1) {
                String operateSymbol = jsonArray.getString(0);
                String value = jsonArray.getString(1);
                switch (operateSymbol) {
                    case "eq":
                        queryWrapper.eq(key, value);
                        break;
                    case "ne":
                        queryWrapper.ne(key, value);
                        break;
                    case "like":
                        queryWrapper.like(key, value);
                        break;
                    case "gt"://大于
                        queryWrapper.gt(key, value);
                        break;
                    case "ge"://大于等于
                        queryWrapper.ge(key, value);
                        break;
                    case "lt"://小于
                        queryWrapper.lt(key, value);
                        break;
                    case "le"://小于等于
                        queryWrapper.le(key, value);
                        break;
                    case "between":
                        Object value1 = jsonArray.getString(2);
                        queryWrapper.between(key, value, value1);
                        break;
                }
            }
        }
        return queryWrapper;
    }


    public <T> QueryWrapper<T> orderBy(QueryWrapper<T> queryWrapper, JSONObject orderby) {
        if (orderby == null) {
            return queryWrapper;
        }
        for (String key : orderby.keySet()) {
            String operateSymbol = orderby.getString(key);
            switch (operateSymbol) {
                case "asc":
                    queryWrapper.orderByAsc(key);
                    break;
                case "desc":
                    queryWrapper.orderByDesc(key);
            }
        }
        return queryWrapper;
    }


}
